<?php

use Core\BeanFactory;
use Core\init\RouterCollector;
use Swoole\Http\Request;
use Swoole\Http\Response;


require_once __DIR__ . "/vendor/autoload.php";
require_once __DIR__ . "/app/config/define.php";
BeanFactory::init();
$router_collector = BeanFactory::getBean(RouterCollector::class);
/**@var $router_collector RouterCollector* */
$dispatcher = $router_collector->getRoutes();
$http = new swoole_http_server("localhost", 9501);
$http->on("request", function (Request $request, Response $response) use ($dispatcher) {
    $myRequest = \Core\http\Request::init($request);
    $myResponse = \Core\http\Response::init($response);
    $routeInfo = $dispatcher->dispatch($myRequest->getMethod(), $myRequest->getUri());
    switch ($routeInfo[0]) {
        case FastRoute\Dispatcher::NOT_FOUND:
            $myResponse->setStatus(404);
            return $myResponse->end();
        case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
            $myResponse->status(405);
            return $myResponse->setStatus();
        case FastRoute\Dispatcher::FOUND:
            $handler = $routeInfo[1];
            $vars = $routeInfo[2];
            $ext_params = [$myRequest, $myResponse];
            $myResponse->setBody($handler($vars, $ext_params));
            return $myResponse->end();
    }
});
$http->start();
